<template>
  <div class="container">
    <h2>收益与抽佣分析</h2>

    <!-- 第一个图表：单数据项对比 -->
    <div class="chart-wrapper">
      <h3>当前总数据对比</h3>
      <div class="chart-box" ref="chartRef1"></div>
    </div>

    <!-- 第二个图表：按日期对比 -->
    <div class="chart-wrapper">
      <h3>按日期趋势对比</h3>
      <div class="chart-box" ref="chartRef2"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import server from "../utils/request.js";

// 图表容器引用
const chartRef1 = ref(null); // 单数据项图表
const chartRef2 = ref(null); // 日期维度图表

// ECharts 实例
let chartInstance1 = null;
let chartInstance2 = null;

// 数据存储
const totalData = ref({ totalMoney: 0, commissionMoney: 0 }); // 总数据
const dateData = ref([]); // 日期维度数据

// 获取总数据（单条）
const fetchTotalData = async () => {
  try {
    const res = await server.get('mysystem');
    if (res.data.code===200){
      totalData.value = res.data.data;
    }
  } catch (error) {
    console.error('总数据获取失败，使用模拟数据', error);
    totalData.value = {
      totalMoney: 85000.50,
      commissionMoney: 12750.75
    };
  }
  renderChart1();
};

// 获取日期维度数据
const fetchDateData = async () => {
  try {
    let res = await server.get('/mysystem/earnings/byDate');
    if(res.data.code===200){
      Object.assign(dateData.value,res.data.data)
      console.log(dateData.value)
    }
  } catch (error) {
    console.error('日期数据获取失败，使用模拟数据', error);
    // 模拟按日期的数据
    dateData.value = [
      { date: '2025-11-01', totalMoney: 12000.30, commissionMoney: 1800.05 },
      { date: '2025-11-02', totalMoney: 15000.50, commissionMoney: 2250.10 },
      { date: '2025-11-03', totalMoney: 13500.25, commissionMoney: 2025.04 },
      { date: '2025-11-04', totalMoney: 16000.80, commissionMoney: 2400.12 },
      { date: '2025-11-05', totalMoney: 18500.65, commissionMoney: 2775.10 }
    ];
  }
  renderChart2();
};

// 渲染第一个图表（单数据项）
const renderChart1 = () => {
  if (chartInstance1) chartInstance1.dispose();
  chartInstance1 = echarts.init(chartRef1.value);

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => {
        let res = `${params[0].name}<br/>`;
        params.forEach(item => {
          res += `${item.seriesName}: ${item.value.toFixed(2)} 元<br/>`;
        });
        return res;
      }
    },
    legend: { data: ['当前收益', '当前抽佣'], top: 10 },
    grid: { left: '15%', right: '15%', bottom: '10%', containLabel: true },
    xAxis: {
      type: 'category',
      data: ['今日数据'], // X轴固定为"总数据"
      axisLabel: { fontSize: 14, fontWeight: 'bold' }
    },
    yAxis: { type: 'value', axisLabel: { formatter: '{value} 元' } },
    series: [
      {
        name: '当前收益',
        type: 'bar',
        data: [totalData.value.totalMoney],
        barWidth: 80,
        itemStyle: { color: '#5470C6' }
      },
      {
        name: '当前抽佣',
        type: 'bar',
        data: [totalData.value.commissionMoney],
        barWidth: 80,
        itemStyle: { color: '#91CC75' }
      }
    ]
  };

  chartInstance1.setOption(option);
};

// 渲染第二个图表（日期维度）
const renderChart2 = () => {
  if (chartInstance2) chartInstance2.dispose();
  chartInstance2 = echarts.init(chartRef2.value);

  // 提取日期和对应数据
  const dates = dateData.value.map(item => item.date);
  const totalMoney = dateData.value.map(item => item.totalmoney);
  const commissionMoney = dateData.value.map(item => item.commissionmoney);

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {type: 'shadow'},
      formatter: (params) => {
        let res = `${params[0].name}<br/>`;
        params.forEach(item => {
          res += `${item.seriesName}: ${item.value.toFixed(2)} 元<br/>`;
        });
        return res;
      }
    },
    legend: {data: ['当日收益', '当日抽佣'], top: 10},
    grid: {left: '3%', right: '4%', bottom: '15%', containLabel: true},
    xAxis: {
      type: 'category',
      data: dates, // X轴为日期
      axisLabel: {
        rotate: 45, // 日期旋转显示，避免重叠
        interval: 0
      }
    },
    yAxis: {type: 'value', axisLabel: {formatter: '{value} 元'}},
    series: [
      {
        name: '当日收益',
        type: 'bar',
        data: totalMoney,
        barWidth: 30,
        itemStyle: {color: '#5470C6'}
      },
      {
        name: '当日抽佣',
        type: 'bar',
        data: commissionMoney,
        barWidth: 30,
        itemStyle: {color: '#91CC75'}
      }
    ]
  };

  chartInstance2.setOption(option);
};

// 组件挂载时初始化
onMounted(() => {
  setTimeout(() => {
    fetchTotalData();
    fetchDateData();
    window.addEventListener('resize', handleResize);
  }, 0);
});

// 窗口大小调整
const handleResize = () => {
  chartInstance1?.resize();
  chartInstance2?.resize();
};

// 组件卸载时清理
onUnmounted(() => {
  if (chartInstance1) chartInstance1.dispose();
  if (chartInstance2) chartInstance2.dispose();
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.container {
  width: 90%;
  margin: 20px auto;
}

.chart-wrapper {
  margin-bottom: 40px;
  padding: 15px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.chart-box {
  width: 100%;
  height: 400px;
  margin-top: 10px;
}

h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
}
</style>